﻿using System;
using System.Threading.Channels;

namespace ORS.OrderRobot.Queue
{
    /// <summary>
    /// 内存消息队列实现
    /// </summary>
    /// <typeparam name="T"></typeparam>
	public class DefaultMessageQueue<T> : IMessageQueue<T>
    {
        private readonly Channel<T> _channel;
        private int _count = 0;

        public DefaultMessageQueue(int capacity = 1000)
        {
            _channel = Channel.CreateBounded<T>(capacity);
        }
        public int Count => _count;

        public async Task EnqueueAsync(T item, CancellationToken cancellationToken = default)
        {
            await _channel.Writer.WriteAsync(item, cancellationToken);
            Interlocked.Increment(ref _count);
        }

        public async Task<T> DequeueAsync(CancellationToken cancellationToken = default)
        {
            var item = await _channel.Reader.ReadAsync(cancellationToken);
            Interlocked.Decrement(ref _count);
            return item;
        }
    }
}

